package controllers

import (
	"github.com/astaxie/beego"
	m"xmy/models/admin"

	"fmt"
)

type UserController struct {
	beego.Controller
}

func (c *UserController)  Login() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "login.html"
}
//返回值封装成json
func (c *UserController) Rsp(status bool, str string) {
	c.Data["json"] = &map[string]interface{}{"status": status, "info": str}
	c.ServeJSON()
}
//用户登录判断
func (c *UserController)  Checklogin() {
	fmt.Println("进来--用户登录判断--控制器来啦")
	isajax := c.GetString("isajax")
	if isajax == "1" {
		username := c.GetString("username")
		password := c.GetString("password")
		fmt.Println("账号：", username)
		fmt.Println("密码：", password)
		user, err := m.CheckLogin(username, password)
		//登录成功后把uesr的信息存进去 userinfo这个session
		c.SetSession("userinfo", user)
		if err == nil && user.Id > 0 {
			c.Rsp(true, "登录成功")
			return
		} else {
			fmt.Println("账号密码错误！！！！")
			fmt.Println("err.Error()-----", err.Error())
			c.Rsp(false, err.Error())
			return
		}

	}
}
//用户模块主面板
func (c *UserController)  Main() {
	//拿到session
	userinfo := c.GetSession("userinfo")
	//拿到session里面的内容
	username := userinfo.(m.Users).Username
	c.Data["username"] = username
	c.TplName = "main.html"
}

//修改密码
func (this *UserController) Changepwd() {
	fmt.Println("进来--用户修改密码--控制器来啦")
	oldpassword := this.GetString("oldpassword")
	newpassword := this.GetString("newpassword")
	repeatpassword := this.GetString("repeatpassword")
	fmt.Println("oldpassword______:", oldpassword)
	fmt.Println("newpassword_________:", newpassword)
	fmt.Println("repeatpassword______:", repeatpassword)
	userinfo := this.GetSession("userinfo")
	if newpassword != repeatpassword {
		this.Rsp(false, "两次输入密码不一致")
	}
	user, err := m.CheckLogin(userinfo.(m.Users).Username, oldpassword)
	fmt.Println("user____________", user)
	if err == nil {
		var u m.Users
		u.Id = user.Id
		u.Password = newpassword
		id, err := m.UpdateUser(&u)
		if err == nil && id > 0 {
			this.Rsp(true, "密码修改成功")
			return
		} else {
			this.Rsp(false, err.Error())
			return
		}
	}
	this.Rsp(false, "密码有误")
}

//退出
func (this *UserController) Logout() {
	//删除session
	this.DelSession("userinfo")
	//退出登录，重定向到登录界面
	this.Ctx.Redirect(302, "/")
}